<?php
// (c) 2010 Philip Clarke, Bouncing Ltd
// license FreeBSD

require('includes/application_top.php');


$debug_logfile_path = DIR_FS_SQL_CACHE . '/Autoupdate_error.log' ;

$errors_to_log = E_ALL ^E_NOTICE;

      @ini_set('log_errors', 1);          // store to file
      @ini_set('log_errors_max_len', 0);  // unlimited length of message output
      @ini_set('display_errors', 0);      // do not output errors to screen/browser/client
      @ini_set('error_log', $debug_logfile_path);  // the filename
      @ini_set('error_reporting', $errors_to_log );    // log only errors of more severity than NOTICE

Header('HTTP/1.1 200 OK');
Header('Content-type: text/plain');
Header('Content-length: 0;');
Header('Connection: close');
flush();
ignore_user_abort();
set_time_limit(0);
ini_set('memory_limit', '64M');



// function to take out some of the duplication


function scheduled_nondupe($tbl, $scheduled){

  global $fc, $fl, $txt, $db ;


###### start scheduled downloads


$sql = "SELECT *, url AS URL FROM `".$scheduled."` INNER JOIN `".$tbl."` ON `".$scheduled."`.module=`".$tbl."`.module WHERE `".$scheduled."`.version=`".$tbl."`.version AND status='S'";

$downloads = $db->Execute($sql);


$a = parse_url($downloads->fields['URL']);

while(!$downloads->EOF){

  clearstatcache();

  if(file_exists(DIR_FS_AUTO_UPDATE_DOWNLOAD.'locks/'.$downloads->fields['filename'])){

    $downloads->MoveNext();

    continue;

  }

  $fc->unlock(DIR_FS_AUTO_UPDATE_DOWNLOAD.'locks');
  $fc->unlock(DIR_FS_AUTO_UPDATE_DOWNLOAD.'locks/'.$downloads->fields['filename']);
  touch(DIR_FS_AUTO_UPDATE_DOWNLOAD.'locks/'.$downloads->fields['filename']);



  $au = new su_httpClient;
  $au->protocolVersion = '1.1' ;
  $au->addHeader('Host', $a['host']);
  $au->addHeader('Connection', 'close');
  $status = $au->Head($downloads->fields['URL']);

  if($status == 200){

    $sql = "UPDATE `".$scheduled."` SET status='D' WHERE module='".$downloads->fields['module']."' AND version='".$downloads->fields['version']."'";

    $db->execute($sql);

    $fc->unlock(DIR_FS_AUTO_UPDATE_DOWNLOAD) ;
    $au->GetStreamed(DIR_FS_AUTO_UPDATE_DOWNLOAD.$downloads->fields['filename'] );
    $fc->relock(DIR_FS_AUTO_UPDATE_DOWNLOAD) ;

    if(dload_check(DIR_FS_AUTO_UPDATE_DOWNLOAD.$downloads->fields['filename'], $downloads->fields['md5key'])){

    // download is verified
      $sql = "UPDATE `".$scheduled."` SET status='V' WHERE module='".$downloads->fields['module']."' AND version='".$downloads->fields['version']."'";

      $db->execute($sql);

      $txt[] = 'Unzipping started. <strong>'.$downloads->fields['module'].'</strong>' ;

      $sql = "INSERT INTO ".TABLE_AUTO_UPDATE_LOG." (logged, error_type, replacing_module, replacing_version, module, version, message) VALUES (NOW(), '', '".$downloads->fields['replacing_module']."', '".$downloads->fields['replacing_version']."', '".$downloads->fields['module']."', '".$downloads->fields['version']."', '".$txt[(sizeof($txt)-1)]."') ";

      $log = $db->execute($sql);

      $zipfile = DIR_FS_AUTO_UPDATE_DOWNLOAD.$downloads->fields['filename'] ;

      $fc->unzip(DIR_FS_AUTO_UPDATE_WORKSPACE, $zipfile);

      $installfile = preg_replace('/\.zip$/', '/install.php', DIR_FS_AUTO_UPDATE_WORKSPACE.$downloads->fields['filename'] ) ;


    // install
    if(file_exists( $installfile )&& is_file( $installfile ) ){

      $sql = "UPDATE `".$scheduled."` SET status='U' WHERE module='".$downloads->fields['module']."' AND version='".$downloads->fields['version']."'";

      $db->execute($sql);

      $txt[] = 'Module unzipped, install.php found. <strong>'.$downloads->fields['module'].'</strong> version <em>'.$downloads->fields['version'].'</em>' ;

      $sql = "INSERT INTO ".TABLE_AUTO_UPDATE_LOG." (logged, error_type, replacing_module, replacing_version, module, version, message) VALUES (NOW(), '', '".$downloads->fields['replacing_module']."', '".$downloads->fields['replacing_version']."', '".$downloads->fields['module']."', '".$downloads->fields['version']."', '".$txt[(sizeof($txt)-1)]."') ";

      $log = $db->execute($sql);

      include_once( $installfile );

	if($install == false){

	$txt[] = 'install.php exited with an <b style="color:red">error</b>. <strong>'.$downloads->fields['module'].'</strong> version <em>'.$downloads->fields['version'].'</em>.
      Check the logs in Admin >> Tools >> Automatic Updates for any installation messages.' ;

	}else{

	$txt[] = 'install.php finished running. <strong>'.$downloads->fields['module'].'</strong> version <em>'.$downloads->fields['version'].'</em>.
      Check the logs in Admin >> Tools >> Automatic Updates for any installation messages.' ;

	}

	$sql = "INSERT INTO ".TABLE_AUTO_UPDATE_LOG." (logged, error_type, replacing_module, replacing_version, module, version, message) VALUES (NOW(), '', '".$downloads->fields['replacing_module']."', '".$downloads->fields['replacing_version']."', '".$downloads->fields['module']."', '".$downloads->fields['version']."', '".$txt[(sizeof($txt)-1)]."') ";

	$log = $db->execute($sql);

      }else{

	$txt[] = 'Module unzipped, install.php file <em>'.$installfile.'</em> not found. <strong>'.$downloads->fields['module'].'</strong> version <em>'.$downloads->fields['version'].'</em>' ;

	$sql = "INSERT INTO ".TABLE_AUTO_UPDATE_LOG." (logged, error_type, replacing_module, replacing_version, module, version, message) VALUES (NOW(), '', '".$downloads->fields['replacing_module']."', '".$downloads->fields['replacing_version']."', '".$downloads->fields['module']."', '".$downloads->fields['version']."', '".$txt[(sizeof($txt)-1)]."') ";

	$log = $db->execute($sql);

      }

// download fails checksum
    }else{

      $sql = "UPDATE `".$scheduled."` SET status='C' WHERE module='".$downloads->fields['module']."' AND version='".$downloads->fields['version']."'";

      $db->execute($sql);

      $txt[] = 'Downloaded zip file did not match checksum. '.$downloads->fields['md5key']. ' probable file corruption.' ;

      $sql = "INSERT INTO ".TABLE_AUTO_UPDATE_LOG." (logged, error_type, replacing_module, replacing_version, module, version, message) VALUES (NOW(), 'fatal', '', '', '".$downloads->fields['module']."', '".$downloads->fields['version']."', '".$txt[(sizeof($txt)-1)]."') ";

      $log = $db->execute($sql);

	$fc->unlock(DIR_FS_AUTO_UPDATE_DOWNLOAD.'locks');
	$fc->unlock(DIR_FS_AUTO_UPDATE_DOWNLOAD.'locks/'.$downloads->fields['filename']);
	unlink(DIR_FS_AUTO_UPDATE_DOWNLOAD.'locks/'.$downloads->fields['filename']);

	$downloads->MoveNext();
	continue;

    }

// download fails weberver error
  }else{

    $sql = "UPDATE `".$scheduled."` SET status='F' WHERE module='".$downloads->fields['module']."' AND version='".$downloads->fields['version']."'";

    $db->execute($sql);

    $txt[] = '
  Optional module: <strong>'.$downloads->fields['module'].'</strong> version <em>'.$downloads->fields['version'].'</em>, download failed webserver error <em>'.$status.'</em>' ;

    $sql = "INSERT INTO ".TABLE_AUTO_UPDATE_LOG." (logged, error_type, module, version, message) VALUES (NOW(), 'fatal', '".$downloads->fields['module']."', '".$downloads->fields['version']."', '".$txt[(sizeof($txt)-1)]."' ) ";

    $log = $db->execute($sql);

  }

    $fc->unlock(DIR_FS_AUTO_UPDATE_DOWNLOAD.'locks');
    $fc->unlock(DIR_FS_AUTO_UPDATE_DOWNLOAD.'locks/'.$downloads->fields['filename']);
    unlink(DIR_FS_AUTO_UPDATE_DOWNLOAD.'locks/'.$downloads->fields['filename']);

    $downloads->MoveNext();

} // end of loop

} // scheduled downloads



function dload_check($file, $md5){

  global $txt, $db, $downloads;

// return true;

  if(md5_file($file)==$md5){

  if(isset($downloads->fields['id']) && $downloads->fields['id'] !=''){

  $sql = "UPDATE ".TABLE_AUTO_UPDATE_AVAILABLE." SET status= 'Y', download_finished='".time()."' WHERE id='".$downloads->fields['id']."'";

  $log = $db->execute($sql);

  }


  $txt[] = 'Zip File <strong>'.basename($file).'</strong> downloaded to <em>'.str_replace(DIR_FS_ADMIN, 'YOUR_ADMIN_FOLDER/', DIR_FS_AUTO_UPDATE_DOWNLOAD).'</em>, checksum verified.';

  $sql = "INSERT INTO ".TABLE_AUTO_UPDATE_LOG." (logged, error_type, replacing_module, replacing_version, module, version, message) VALUES (NOW(), '', '".$downloads->fields['replacing_module']."', '".$downloads->fields['replacing_version']."', '".$downloads->fields['module']."', '".$downloads->fields['version']."', '".$txt[(sizeof($txt)-1)]."') ";

  $log = $db->execute($sql);

  return true;

  }else{
    return false;
  }

}


class su_httpClient extends httpClient{

  function GetStreamed($filename){

    global $db, $txt, $fc;

    $rh = fsockopen($this->url['host'], 80);
    if($rh){
    if(file_exists($filename)){
      $fc->unlock($filename);
    }

    $fp = fopen($filename, 'wb+');
    $out = "GET ".$this->url['path']." HTTP/1.0\r\n";
    $out .= "Host: ".$this->url['host']."\r\n";
    $out .= "Connection: Close\r\n\r\n";
    fwrite($rh, $out);
    $write = false;
    while (!feof($rh)) {
        $str = fgets($rh, 4096);
	if(!$write && trim($str)==''){
	  $write = true;
	  continue;
	}
	if($write == true){
	  fwrite($fp, $str, strlen($str));
	}
    }
    fclose($fp);
    fclose($rh);

      return true;

    }else{
      $sql = "UPDATE `".TABLE_MODULES_SCHEDULED."` SET status='F' WHERE module='".$downloads->fields['module']."' AND version='".$downloads->fields['version']."'";

      $db->execute($sql);

      $txt[] = '
Optional module: <strong>'.$downloads->fields['module'].'</strong> version <em>'.$downloads->fields['version'].'</em>, download failed webserver error <em>'.$status.'</em>' ;

      $sql = "INSERT INTO ".TABLE_AUTO_UPDATE_LOG." (logged, error_type, module, version, message) VALUES (NOW(), 'fatal', '".$downloads->fields['module']."', '".$downloads->fields['version']."', '".$txt[(sizeof($txt)-1)]."' ) ";

      $log = $db->execute($sql);


    }

  }

}


// fl now deprecated
$fc = $fl = new smz_filesystem ;


function su_update_mail($txt){

  $txt = join("\n",$txt) ;

  $email_to = MODULE_AUTO_UPDATE_EMAIL ;

  if(trim(MODULE_AUTO_UPDATE_EMAIL)==''){
    $email_to = STORE_OWNER_EMAIL_ADDRESS;
  }

  zen_mail('', $email_to, 'Auto Update Message', "\n".strip_tags($txt), 'ShopUpgraded - Auto Update Module', $email_to, array('EMAIL_MESSAGE_HTML'=> nl2br($txt) ), 'updates_extra' );

}

$txt = array();

if(trim(AUTOINSTALL_CALLER) == ''){

  $txt[] = 'The auto update function is now locked to one address. '.$_SERVER['REMOTE_ADDR'];

  $sql = "UPDATE `".TABLE_CONFIGURATION."` SET configuration_value='".$_SERVER['REMOTE_ADDR']."' WHERE configuration_key='AUTOINSTALL_CALLER'";

  $db->Execute($sql);

  define('MODULE_AUTO_UPDATE_CALLER', $_SERVER['REMOTE_ADDR']);

}

define('MODULE_AUTO_UPDATE_CALLER', AUTOINSTALL_CALLER);


if(MODULE_AUTO_UPDATE_CALLER != $_SERVER['REMOTE_ADDR'] && $_SERVER['REMOTE_ADDR'] != '::1'){

  $txt[] = 'Auto update failure. Update page is locked to <em>'.MODULE_AUTO_UPDATE_CALLER.'</em> but was called by <em>'.$_SERVER['REMOTE_ADDR'].'</em>.';

  $sql = "INSERT INTO ".TABLE_AUTO_UPDATE_LOG." (logged, error_type, message) VALUES (NOW(), 'fatal', '".$txt[(sizeof($txt)-1)]."') ";

  $log = $db->execute($sql);

  su_update_mail($txt) ;

  exit;
}


if(AUTOINSTALL_SETTING < 1){
  exit;
}


// exit;
// stage 1
  // check for updates on modules, add it to the "available table"
// stage 2
  // download from the available table mark as not to be downloaded
// stage 3
  // extract and verify

// get the installed modules that are not marked as being available

$sql = "SELECT au.module, au.version FROM ".TABLE_AUTO_UPDATE." au LEFT JOIN ".TABLE_AUTO_UPDATE_AVAILABLE." aul ON au.module=aul.replacing_module WHERE replacing_module IS NULL";

$q = $db->execute($sql);
$installed_modules = array();

while(!$q->EOF){
  $installed_modules[$q->fields['module']] = $q->fields['version'] ;
  $q->MoveNext();
}

$au = new httpClient;
$au->protocolVersion = '1.0' ;
$au->addHeader('Host', MODULE_AUTO_UPDATE_SERVER);
$au->addHeader('Connection', 'close');
$status = $au->Get('http://'.MODULE_AUTO_UPDATE_SERVER.'/'.MODULE_AUTO_UPDATE_URI.'?updates');



if($status != 200){

  $txt[] = 'Could not connect to update server. Webserver '.$status.' error.';

  $sql = "INSERT INTO ".TABLE_AUTO_UPDATE_LOG." (logged, error_type, message) VALUES (NOW(), 'fatal', '".$txt[(sizeof($txt)-1)]."') ";

  $db->execute($sql);

  su_update_mail($txt) ;

  exit;

}



  foreach(explode("\n", str_replace("\r", "", $au->responseBody)) as $line){
    if(trim($line)!=''){
    $module = explode('|', $line);

      if(isset($installed_modules[$module[0]]) && version_compare($installed_modules[$module[0]], $module[1]) ){

	$sql = "INSERT INTO ".TABLE_AUTO_UPDATE_AVAILABLE." (replacing_module, replacing_version, module, version, status, md5key, url, filename) VALUES ('".$module[0]."', '".$installed_modules[$module[0]]."', '".$module[0]."', '".$module[1]."', 'P', '".$module[3]."', '".$module[2]."', '".$module[7]."')";

	$db->execute($sql);

	$sql = "UPDATE ".TABLE_AUTO_UPDATE." SET last_checked = ".time()." WHERE module = '".$module[0]."'";

	$db->execute($sql);

      }

    }
  } // end of exploding response body


######## get optional modules every 24 hours ;


$au = new httpClient;
$au->protocolVersion = '1.0' ;
$au->addHeader('Host', MODULE_AUTO_UPDATE_SERVER);
// $au->addHeader('Host', 'localhost');
$au->addHeader('Connection', 'close');
$status = $au->Get('http://'.MODULE_AUTO_UPDATE_SERVER.'/'.MODULE_AUTO_UPDATE_URI.'?optional');
// $status = $au->Get('http://localhost/test/updates.php?optional');


if((int)$status == 200){

  $sql = array();

  $sql[] = "DELETE FROM `".TABLE_MODULES_OPTIONAL."` ";

  foreach(explode("\n", str_replace("\r", "", $au->responseBody)) as $line){
    if(trim($line)!=''){
    $module = explode('|', $line);

	$sql[] = "INSERT INTO `".TABLE_MODULES_OPTIONAL."` (module, version, url,  description, licence, md5key, authors, filename, notes) VALUES ('".$module[0]."', '".$module[1]."', '".$module[2]."', '".str_replace("'", "\'", $module[4])."', '".$module[5]."', '".$module[3]."', '".$module[6]."', '".$module[7]."', '".$module[8]."')";

    }
  } // end of exploding response body

  foreach($sql as $db_exe){
     	$db->Execute($db_exe);
  }

}

####### bof optional module download

######## gets patches every 24 hours ;


$au = new httpClient;
$au->protocolVersion = '1.0' ;
$au->addHeader('Host', MODULE_AUTO_UPDATE_SERVER);
// $au->addHeader('Host', 'localhost');
$au->addHeader('Connection', 'close');
$status = $au->Get('http://'.MODULE_AUTO_UPDATE_SERVER.'/'.MODULE_AUTO_UPDATE_URI.'?patches');
// $status = $au->Get('http://localhost/test/updates.php?patches');


if((int)$status == 200){

  $sql = "SELECT COUNT(*) AS patches FROM `".TABLE_PATCHES."` ";

  $db->Execute($sql);

  $original_patches = $db->fields['patches'];

  $sql = array();

  $sql[] = "DELETE FROM `".TABLE_PATCHES."` ";

  foreach(explode("\n", str_replace("\r", "", $au->responseBody)) as $line){
    if(trim($line)!=''){
    $module = explode('|', $line);

	$sql[] = "INSERT INTO `".TABLE_PATCHES."` (module, version, url,  description, licence, md5key, authors, filename, notes) VALUES ('".$module[0]."', '".$module[1]."', '".$module[2]."', '".str_replace("'", "\'", $module[4])."', '".$module[5]."', '".$module[3]."', '".$module[6]."', '".$module[7]."', '".$module[8]."')";

    }
  } // end of exploding response body

  foreach($sql as $db_exe){
     	$db->Execute($db_exe);
  }

  $sql = "SELECT COUNT(*) AS patches FROM `".TABLE_PATCHES."` ";

  $db->Execute($sql);

  $new_patches = $db->fields['patches'];


}

####### bof optional module patches

###### patches get inserted into scheduled automatically ######

$sql = "SELECT module, version FROM ".TABLE_PATCHES;

$patches = $db->Execute($sql);

$patch = array();

while(!$patches->EOF){

  $patch[$patches->fields['module']] = $patches->fields['version'] ;

  $sql = "SELECT * FROM ".TABLE_PATCHES_SCHEDULED." WHERE module = '".$patches->fields['module']."' AND version = '".$patches->fields['version']."'";

  $tmp = $db->Execute($sql);

  if($tmp->RecordCount()==0){

    $sql= "INSERT INTO ".TABLE_PATCHES_SCHEDULED." (module, version, status) VALUES('".$patches->fields['module']."', '".$patches->fields['version']."', 'S') ";

    $db->Execute($sql);

  }

  $patches->MoveNext();
}

###### end of patched insertion ########



##### begin install scheduled patches ######

scheduled_nondupe(TABLE_PATCHES, TABLE_PATCHES_SCHEDULED);

##### end install scheduled patches ######



##### begin install scheduled modules ######

scheduled_nondupe(TABLE_MODULES_OPTIONAL, TABLE_MODULES_SCHEDULED);

##### end install scheduled modules ######






// acheived only marks it as available the one time.

// stage 2
// select from the available table




$sql = "SELECT aua.* FROM ".TABLE_AUTO_UPDATE_AVAILABLE." aua INNER JOIN ".TABLE_AUTO_UPDATE." au ON au.module=aua.module WHERE status = 'P' ";

$downloads = $db->execute($sql);


while(!$downloads->EOF){

// just in case another process is trying to download one of the files.
if(file_exists(DIR_FS_AUTO_UPDATE_DOWNLOAD.'locks/'.$downloads->fields['replacing_module']) || AUTOINSTALL_SETTING < 2) {

  if(AUTOINSTALL_SETTING < 2){
  $txt[] = '
Upgrade available, for <strong>'.$downloads->fields['module'].'</strong> version <em>'.$downloads->fields['version'].'</em>, automatic downloads have been disabled by Store owner.' ;
  }else{
  $txt[] = '
Upgrade available, for <strong>'.$downloads->fields['module'].'</strong> version <em>'.$downloads->fields['version'].'</em>' ;
  }

  $sql = "INSERT INTO ".TABLE_AUTO_UPDATE_LOG." (logged, error_type, replacing_module, replacing_version, module, version, message) VALUES (NOW(), '', '".$downloads->fields['replacing_module']."', '".$downloads->fields['replacing_version']."', '".$downloads->fields['module']."', '".$downloads->fields['version']."', '".$txt[(sizeof($txt)-1)]."' ) ";

  $log = $db->execute($sql);


  $downloads->MoveNext();
  continue;
}

$fc->unlock(DIR_FS_AUTO_UPDATE_DOWNLOAD.'locks');
$fc->unlock(DIR_FS_AUTO_UPDATE_DOWNLOAD.'locks/'.$downloads->fields['replacing_module']);
touch(DIR_FS_AUTO_UPDATE_DOWNLOAD.'locks/'.$downloads->fields['replacing_module']);

 $sql = "UPDATE ".TABLE_AUTO_UPDATE_AVAILABLE." SET download_started='".time()."' WHERE id='".$downloads->fields['id']."'";

 $log = $db->execute($sql);

  $txt[] = '
Upgrade available, download started for <strong>'.$downloads->fields['module'].'</strong> version <em>'.$downloads->fields['version'].'</em>' ;

  $sql = "INSERT INTO ".TABLE_AUTO_UPDATE_LOG." (logged, error_type, replacing_module, replacing_version, module, version, message) VALUES (NOW(), '', '".$downloads->fields['replacing_module']."', '".$downloads->fields['replacing_version']."', '".$downloads->fields['module']."', '".$downloads->fields['version']."', '".$txt[(sizeof($txt)-1)]."' ) ";

  $log = $db->execute($sql);


$au = new su_httpClient;
$au->protocolVersion = '1.0' ;
$au->addHeader('Host', MODULE_AUTO_UPDATE_SERVER);
$au->addHeader('Connection', 'close');

$status = $au->Head($downloads->fields['URL']);

if($status != 200 ){

  $sql = "UPDATE ".TABLE_AUTO_UPDATE_AVAILABLE." SET status= 'E', download_finished='NULL' WHERE id='".$downloads->fields['id']."'";

  $log = $db->execute($sql);

  $txt[] = 'Upgrade file not found, <strong>'.$downloads->fields['URL'].'</strong>,  Webserver <em>'.$status.'</em> error.' ;

  $sql = "INSERT INTO ".TABLE_AUTO_UPDATE_LOG." (logged, error_type, replacing_module, replacing_version, module, version, message) VALUES (NOW(), 'fatal', '".$downloads->fields['replacing_module']."', '".$downloads->fields['replacing_version']."', '".$downloads->fields['module']."', '".$downloads->fields['version']."', '".$txt[(sizeof($txt)-1)]."') ";

  $log = $db->execute($sql);

  $fc->unlock(DIR_FS_AUTO_UPDATE_DOWNLOAD.'locks');
  $fc->unlock(DIR_FS_AUTO_UPDATE_DOWNLOAD.'locks/'.$downloads->fields['replacing_module']);
  unlink(DIR_FS_AUTO_UPDATE_DOWNLOAD.'locks/'.$downloads->fields['replacing_module']);

  $downloads->MoveNext();

  continue;

}

$fc->unlock(DIR_FS_AUTO_UPDATE_DOWNLOAD) ;
$au->GetStreamed(DIR_FS_AUTO_UPDATE_DOWNLOAD.basename($downloads->fields['URL']));
$fc->relock(DIR_FS_AUTO_UPDATE_DOWNLOAD) ;




// download check.

if(dload_check(DIR_FS_AUTO_UPDATE_DOWNLOAD.basename($downloads->fields['URL']), $downloads->fields['md5key'])){

  $fc->unlock(DIR_FS_AUTO_UPDATE_DOWNLOAD.'locks');
  $fc->unlock(DIR_FS_AUTO_UPDATE_DOWNLOAD.'locks/'.$downloads->fields['replacing_module']);
  unlink(DIR_FS_AUTO_UPDATE_DOWNLOAD.'locks/'.$downloads->fields['replacing_module']);

// download fails checksum
}else{

  $sql = "UPDATE ".TABLE_AUTO_UPDATE_AVAILABLE." SET status= 'E', download_finished='".time()."' WHERE id='".$downloads->fields['id']."'";

  $log = $db->execute($sql);

  $txt[] = 'Downloaded zip file did not match checksum. '.$downloads->fields['md5key']. ' probable file corruption.' ;

  $sql = "INSERT INTO ".TABLE_AUTO_UPDATE_LOG." (logged, error_type, replacing_module, replacing_version, module, version, message) VALUES (NOW(), 'fatal', '".$downloads->fields['replacing_module']."', '".$downloads->fields['replacing_version']."', '".$downloads->fields['module']."', '".$downloads->fields['version']."', '".$txt[(sizeof($txt)-1)]."') ";

  $log = $db->execute($sql);

  $fc->unlock(DIR_FS_AUTO_UPDATE_DOWNLOAD.'locks');
  $fc->unlock(DIR_FS_AUTO_UPDATE_DOWNLOAD.'locks/'.$downloads->fields['replacing_module']);
  unlink(DIR_FS_AUTO_UPDATE_DOWNLOAD.'locks/'.$downloads->fields['replacing_module']);

  $downloads->MoveNext();

  continue;

}

  $downloads->MoveNext();

} // end of looping through downloads.


sleep(3);

$sql = "SELECT * FROM ".TABLE_AUTO_UPDATE_AVAILABLE." WHERE status = 'Y'";

$downloads = $db->execute($sql);

while(!$downloads->EOF){

// just in case another process is trying to download one of the files.
if(file_exists(DIR_FS_AUTO_UPDATE_DOWNLOAD.'locks/'.$downloads->fields['replacing_module']) || AUTOINSTALL_SETTING < 3) {
  $downloads->MoveNext();
  continue;
}
$fc->unlock(DIR_FS_AUTO_UPDATE_DOWNLOAD.'locks');
$fc->unlock(DIR_FS_AUTO_UPDATE_DOWNLOAD.'locks/'.$downloads->fields['replacing_module']);
touch(DIR_FS_AUTO_UPDATE_DOWNLOAD.'locks/'.$downloads->fields['replacing_module']);

  $txt[] = 'Unzipping started. <strong>'.$downloads->fields['module'].'</strong>' ;

  $sql = "INSERT INTO ".TABLE_AUTO_UPDATE_LOG." (logged, error_type, replacing_module, replacing_version, module, version, message) VALUES (NOW(), '', '".$downloads->fields['replacing_module']."', '".$downloads->fields['replacing_version']."', '".$downloads->fields['module']."', '".$downloads->fields['version']."', '".$txt[(sizeof($txt)-1)]."') ";

  $log = $db->execute($sql);

$zipfile = DIR_FS_AUTO_UPDATE_DOWNLOAD.basename($downloads->fields['URL']) ;

$fc->unzip(DIR_FS_AUTO_UPDATE_WORKSPACE, $zipfile);

$installfile = preg_replace('/\.zip$/', '/install.php', DIR_FS_AUTO_UPDATE_WORKSPACE.basename($downloads->fields['URL']) ) ;

if(file_exists( $installfile ) ){

  // system is finished (flagged) possibly failed, but all downloads and unzipping has been done.
  $sql = "UPDATE ".TABLE_AUTO_UPDATE_AVAILABLE." SET status= 'F' WHERE id='".$downloads->fields['id']."'";

  $log = $db->execute($sql);

  if(AUTOINSTALL_SETTING == 4){

  $txt[] = 'Module unzipped, install.php found. <strong>'.$downloads->fields['module'].'</strong> version <em>'.$downloads->fields['version'].'</em>' ;

  $sql = "INSERT INTO ".TABLE_AUTO_UPDATE_LOG." (logged, error_type, replacing_module, replacing_version, module, version, message) VALUES (NOW(), '', '".$downloads->fields['replacing_module']."', '".$downloads->fields['replacing_version']."', '".$downloads->fields['module']."', '".$downloads->fields['version']."', '".$txt[(sizeof($txt)-1)]."') ";

  $log = $db->execute($sql);

  include_once( $installfile );

  if($install == false){
  $txt[] = 'install.php exited with an <b style="color:red">error</b>. <strong>'.$downloads->fields['module'].'</strong> version <em>'.$downloads->fields['version'].'</em>.
Check the logs in Admin >> Tools >> Automatic Updates for any installation messages.' ;
  }else{
  $txt[] = 'install.php finished running. <strong>'.$downloads->fields['module'].'</strong> version <em>'.$downloads->fields['version'].'</em>.
Check the logs in Admin >> Tools >> Automatic Updates for any installation messages.' ;
  }

  $sql = "INSERT INTO ".TABLE_AUTO_UPDATE_LOG." (logged, error_type, replacing_module, replacing_version, module, version, message) VALUES (NOW(), '', '".$downloads->fields['replacing_module']."', '".$downloads->fields['replacing_version']."', '".$downloads->fields['module']."', '".$downloads->fields['version']."', '".$txt[(sizeof($txt)-1)]."') ";

  $log = $db->execute($sql);

  }else{

  $txt[] = '<strong>'.$downloads->fields['module'].'</strong> version <em>'.$downloads->fields['version'].'</em> Module unzipped, Awaiting manual installation in <em>'.str_replace(DIR_FS_ADMIN, 'YOUR_ADMIN_AREA/', DIR_FS_AUTO_UPDATE_WORKSPACE).'</em>' ;

  $sql = "INSERT INTO ".TABLE_AUTO_UPDATE_LOG." (logged, error_type, replacing_module, replacing_version, module, version, message) VALUES (NOW(), '', '".$downloads->fields['replacing_module']."', '".$downloads->fields['replacing_version']."', '".$downloads->fields['module']."', '".$downloads->fields['version']."', '".$txt[(sizeof($txt)-1)]."') ";

  $log = $db->execute($sql);

  }

  $fc->unlock(DIR_FS_AUTO_UPDATE_DOWNLOAD.'locks');
  $fc->unlock(DIR_FS_AUTO_UPDATE_DOWNLOAD.'locks/'.$downloads->fields['replacing_module']);
  unlink(DIR_FS_AUTO_UPDATE_DOWNLOAD.'locks/'.$downloads->fields['replacing_module']);


}else if(AUTOINSTALL_SETTING == 4){

  $txt[] = 'No install.php found, exiting with nothing to do. <strong>'.$downloads->fields['module'].'</strong> version <em>'.$downloads->fields['version'].'</em>' ;

  $sql = "INSERT INTO ".TABLE_AUTO_UPDATE_LOG." (logged, error_type, replacing_module, replacing_version, module, version, message) VALUES (NOW(), 'fatal', '".$downloads->fields['replacing_module']."', '".$downloads->fields['replacing_version']."', '".$downloads->fields['module']."', '".$downloads->fields['version']."', '".$txt[(sizeof($txt)-1)]."') ";

  $log = $db->execute($sql);

  $fc->unlock(DIR_FS_AUTO_UPDATE_DOWNLOAD.'locks');
  $fc->unlock(DIR_FS_AUTO_UPDATE_DOWNLOAD.'locks/'.$downloads->fields['replacing_module']);
  unlink(DIR_FS_AUTO_UPDATE_DOWNLOAD.'locks/'.$downloads->fields['replacing_module']);

//   $downloads->MoveNext();

//   continue;

}

  $downloads->MoveNext();

}

  $fc->relock(DIR_FS_AUTO_UPDATE_DOWNLOAD.'locks');


  if(sizeof($txt)>0){
    su_update_mail($txt) ;
  }

exit;
